package cn.wolfcode.shop.controller;

import cn.wolfcode.shop.api.domain.Catalog;
import cn.wolfcode.shop.api.service.ICatalogService;
import cn.wolfcode.shop.api.vo.JsonResultVo;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class CatalogController {

    @Reference
    private ICatalogService catalogService;

    /**
     * 跳转到管理分类的页面
     * @return
     */
    @RequestMapping("goods")
    public String goods(){
        return "catalog/catalog";
    }

    /**
     * 初始化树,查找对应节点的子节点
     * @param id
     * @return
     */
    @RequestMapping("/catalog/get")
    @ResponseBody
    public List<Catalog> getTree(Long id){
        if (id == null){
            List<Catalog> catalogs = catalogService.selecRootTree();
            return catalogs;
        }else {
            List<Catalog> catalogs = catalogService.selectSonTree(id);
            return catalogs;
        }
    }

    /**
     * 跳转到编辑分类的页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/catalog/add/{id}")
    public String editTree(@PathVariable("id") Long id, Model model){
        Catalog catalog = catalogService.get(id);
        model.addAttribute("catalog",catalog);
        return "catalog/catalog_input";
    }

    /**
     * 分类的保存和保存和编辑
     * @param catalog
     * @return
     */
    @RequestMapping("/catalog/save")
    @ResponseBody
    public JsonResultVo saveOrUpdate(Catalog catalog){
        JsonResultVo vo = new JsonResultVo(true,"操作成功!",null);
        try {
            if(catalog.getId() != null){
                Catalog oldCatalog = catalogService.get(catalog.getId());
                oldCatalog.setCode(catalog.getCode());
                oldCatalog.setName(catalog.getName());
                catalogService.update(oldCatalog);
            }else {
                catalogService.save(catalog);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResultVo(false,e.getMessage(),null);
        }
        return vo;
    }

    /**
     * 分类的删除
     * @param id
     * @return
     */
    @RequestMapping("/catalog/delete/{id}")
    @ResponseBody
    public JsonResultVo delete(@PathVariable("id") Long id){
        JsonResultVo vo = new JsonResultVo(true,"删除成功!",null);
        try {
            catalogService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResultVo(false,e.getMessage(),null);
        }
        return vo;
    }
}
